<template>
  <div class="DivisionCarbon">
    <div class="leftbox">
      <el-autocomplete
              class="inline-input"
              v-model="filterText"
              size="small"
              style="margin-bottom: 10px;width:100%"
              :fetch-suggestions="querySearch"
              placeholder="输入关键字进行过滤"
              :trigger-on-focus="true"
              value-key="name"
              :debounce='300'
              @select="handleSelect"
            ></el-autocomplete>
      <div class="treebox">
        <el-tree
        lazy
        class="filter-tree"
        show-checkbox
        :default-expanded-keys="array"
        node-key="id"
        :highlight-current="true"
        :load="loadNode"
        :props="defaultProps"
        @check="handleNodeClick"
        @node-click="nodeclick"
        ref="tree">
       </el-tree>
      </div>
    </div>
    <div class="liftbox">
      <div class="righttop">
        <el-form ref="form" >
            <el-col :span="6">
              <el-form-item label="">
                <el-radio-group v-model="radio3" size="small" style="margin-right: 20px;">
                  <el-radio-button label="2">月</el-radio-button>
                  <el-radio-button label="3">年</el-radio-button>
                </el-radio-group>
                <el-date-picker v-if="radio3=='2'" v-model="value2" type="month" value-format="yyyy-MM" placeholder="选择月" size="small" style="width: 60%;"></el-date-picker>
                <el-date-picker v-else v-model="value3" type="year" value-format="yyyy" placeholder="选择年" size="small" style="width: 60%;"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="18" style="text-align: right;">
              <el-button size="small" @click="chongzhi">重 置</el-button>
              <el-button type="primary" size="small" @click="submit">查 询</el-button>
            </el-col>
        </el-form>
      </div>
      <div class="rightbody">
        <div class="righttitle">
          <div>工厂碳排统计</div>
          <div class="titlebutt"><TopTile  @command="command" @daochu="daochu" @shuaxin="shuaxin"></TopTile></div>
        </div>
        <div class="tableandechart">
          <!-- 表区域 -->
          <div class="table">
            <el-table
              :size="issize"
              border
              ref="tableref"
              :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
              v-loading="loading"
              height="calc(100% - 1px)"
              :data="tableData"
               highlight-current-row
               @current-change="handleCurrentChange"
              style="width: 100%">
              <el-table-column
              v-if="tableData.length"
                type="index"
                fixed
                align="center"
                label="序号"
                width="70">
              </el-table-column>
              <el-table-column
              v-if="tableData.length"
                prop="name"
                fixed
                width="120"
                label="部门">
              </el-table-column>
              <el-table-column v-for="(item,index) in tablecolumnlist" :key="index" :label="item">
                <el-table-column
                  :prop="item.replace(/-/g, '') + '_dian'"
                  label="电量(kWh)"
                  align="right"
                  width="120">
                </el-table-column>
                <el-table-column
                  :prop="item.replace(/-/g, '') + '_tan'"
                  label="碳排(t)"
                   align="right"
                  width="120">
                </el-table-column>
              </el-table-column>
              <el-table-column v-for="(item,index) in endarr" :key="index-1" :label="item" width="240" fixed="right">
                <el-table-column
                  :prop="item.replace(/-/g, '') + '_dian'"
                  label="电量(kWh)"
                  align="right"
                  width="120">
                </el-table-column>
                <el-table-column
                  :prop="item.replace(/-/g, '') + '_tan'"
                  label="碳排(t)"
                   align="right"
                  width="120">
                </el-table-column>
              </el-table-column>
            </el-table>
          </div>
          <!-- 图表区域 -->
           <div class="totalechart" ref="totalechart"></div>
        </div>
        <!-- dialog弹窗区域 -->
         <div>
          <el-dialog
          :title="columnvalue.name"
          :visible.sync="dialogVisible"
          width="50%">
          <div style="height: 350px;" ref="columnechart"></div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false" size="small">取 消</el-button>
            </span>
          </el-dialog>
         </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getKeywordListApi } from '@/api/Ledger3'
import TopTile from '@/components/TopTitle/index.vue'
import { getDepartmentTreeApi, } from '@/api/energy-consumption/Department/Query'
import { getfenorgongquxianapi, getfenghuorgongapi } from '@/api/energy-consumption/CarbonEmissions/Department'
import { getgenjiedianapi, getzijidianapi } from '@/api/energy-consumption/Basic-information/gateway'
import {exportexcel} from '@/utils/excel'
export default {
  name: 'CallPoliceIndex',
  components:{
    TopTile
  },
  data() {
    return {
      data: [],
      array:[],
      treelist:[],
      radio3:'2',
      value2:'',
      value3: '',
      loading:false,
      issize: 'medium',
      filterText:'',
      defaultProps: {
        label: 'name',
        children:'sonList'
      },
      tableData: [],
      tablecolumnlist:[],
      columnvalue:{},
      dialogVisible: false,
      endarr:[]
    };
  },

  async mounted() {
    const { data: { list } } = await getDepartmentTreeApi()
    this.data = list
    this.$refs.tree.setCheckedKeys([list[0].id],false)
    this.gettime()
    setTimeout(()=>this.nodeclick(),200)
  },

  methods: {
    async submit() {
      if (this.treelist.length) {
        this.getdatalist()
        this.gettotaltubiao()
      } else {
        this.tablecolumnlist=[]
        this.tableData = []
        this.endarr=[]
        this.gettotaltubiao(true)
      }
    },
    // 获取表格数据
    async getdatalist() {
      this.loading = true
      const classIdNames =[]
      this.treelist.map(ele =>classIdNames.push(ele.id+'_'+ele.name) )
      const { data: { list } } = await getfenghuorgongapi({
        dateString: this.radio3 == '2' ? this.value2 : this.value3,
        dateType:this.radio3,classIdNames:classIdNames.join(',')
      })
      this.loading=false
      if(!list.length) return this.tableData=[]
      // 获取表头数据
      this.tablecolumnlist = Object.keys(list[0]?.valueMap)
      this.endarr = this.tablecolumnlist.splice(this.tablecolumnlist.length - 1, 1)
      // 处理表格数据
      const array=list.map(item => {
        let newItem = { name: item.name };
        Object.keys(item.valueMap).forEach(key => {
            let values = item.valueMap[key].split(',');
            newItem[key.replace(/-/g, '') + '_dian'] = values[0];
            newItem[key.replace(/-/g, '') + '_tan'] = values[1];
        });
        return newItem;
      })
      this.tableData = array
      this.$nextTick(() =>this.$refs.tableref.doLayout())
    },
    // 表格单选
    handleCurrentChange(val) {
      this.columnvalue = val
      this.dialogVisible = true
      setTimeout(()=>this.getcomponech(val),1)
    },
    // 树节点点击
    handleNodeClick(data, obj) {
      this.treelist = this.$refs.tree.getCheckedNodes(false,true)
      this.submit()
    },
    nodeclick(val) {
      this.treelist = this.$refs.tree.getCheckedNodes(false,true)
      this.submit()
    },
    // 树节点搜索
    async querySearch(queryString, cb) {
      setTimeout(async () => {
        const res = await getKeywordListApi({ name: queryString })
        const restaurants = res.data.list
        cb(restaurants)
      }, 500)
      // 调用 callback 返回建议列表的数据
    },
    // 搜索选择
    handleSelect (item) {
      // 拿到父节点id 添加至展开数组中用以展开选中节点的父节点
      const newarr = item.pathId.split(',')
      for (let i = 0; i < newarr.length; i++) {
        if (newarr[i]) {
          this.array.push(newarr[i])
        }
      }
      // push方法是同步任务 但是节点展开需要掉接口是异步任务 如果此时直接调用选中节点高亮方法由于节点还未完全展开所以拿不到所选中的节点信息
      // 编写递归函数根据getNode判断选中的节点是否完全展开
      function getgaoliang (that) {
        const node = that.$refs.tree.getNode(item)
        // node不为null说明节点已经完全展开 所选节点已经存在 调用方法高亮选中节点以及模拟点击该节点
        if (node) {
          that.handleNodeClick(node.data)
          that.$refs.tree.setCurrentKey(String(item.id))
        } else {
          // 如果node为null说明节点还未完全展开 继续调用函数
          setTimeout(() => {
            getgaoliang(that)
          }, 500)
        }
      }
      getgaoliang(this)
    },
    // 树组件懒加载
    async loadNode(node, resolve) {
      const res = await getgenjiedianapi({ treeModel: 'ENERGY_FACTORY_SET_TREE' })
      const ress = await getzijidianapi(res.data.list[0])
      if (node.level === 0) {
        return resolve(ress.data.list)
      } else if (node.level >0) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      }
    },
    // 调节表格密度
     command(val) {
      if (val === '默认') {
        this.issize = 'medium'
      } else if (val === '中等') {
        this.issize = 'small'
      } else {
        this.issize = 'mini'
      }
    },
    // 导出
    daochu() {
      const classIdNames =[]
      this.treelist.map(ele =>classIdNames.push(ele.id+'_'+ele.name) )
      exportexcel('ecm-microservice-biz/ecm/carbon/statistics/factory/exportExcel', {
        dateString: this.radio3 == '2' ? this.value2 : this.value3,
        dateType:this.radio3,classIdNames:classIdNames.join(','),factoryFlag:'1'
      },'工厂碳排')
    },
    // 刷新列表
    shuaxin() {
      this.submit()
      this.$message.success('数据刷新成功')
    },
    // 重置
    chongzhi() {
      this.radio3 = '2'
      this.gettime()
      this.submit()
    },
    // 获取当前时间戳
    gettime() {
      const date = new Date()
      const year = date.getFullYear() // 年
      const mon = date.getMonth() + 1 // 月
      const month =mon<10?'0'+mon:mon
      this.value3 = year.toString()
      this.value2 = year + '-' + month
    },
    // 树节点过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 获取部门图表
    getcomponech(obj) {
      var chartDom = this.$refs.columnechart
      var myChart = echarts.init(chartDom);
      var option;
      // 提取日期和对应的_dian和_tan数据，排除合计数据
      const dates = Object.keys(obj).filter(key => key.includes('_dian') && !key.includes('合计'));
      const dianData = dates.map(date => parseFloat(obj[date]));
      const tanData = dates.map(date => parseFloat(obj[date.replace('_dian', '_tan')]));
      const formattedDates = dates.map(date => date.replace('_dian', ''));
      // 改造option
       option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: ['电量', '碳排']
         },
         grid: {
          left: '3%',
          right: '1%',
          bottom: '2%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: formattedDates, // 使用提取出来的日期数据
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '',
          }
        ],
        series: [
          {
            name: '电量',
            type: 'bar',
            data: dianData // 使用提取出来的_dian数据
          },
          {
            name: '碳排',
            type: 'bar',
            data: tanData // 使用提取出来的_tan数据
          }
        ]
      };
      myChart.clear();
      option && myChart.setOption(option);
    },
    // 获取总量图表
    async gettotaltubiao(flag) {
      var chartDom = this.$refs.totalechart
      var myChart = echarts.init(chartDom);
      var option;
      const classIdNames =[]
      this.treelist.map(ele =>classIdNames.push(ele.id+'_'+ele.name) )
      if (!flag) {
        var {data:{list}}=await getfenorgongquxianapi({
        dateString: this.radio3 == '2' ? this.value2 : this.value3,
        dateType:this.radio3,classIdNames:classIdNames.join(','),
      })
      var timePoints = list.map(ele => ele.name);
        var series = list.map(ele => {
          return {
            name: ele.name,
            type: 'bar',
            data: ele.datalist.map(item => item.valueReading),
          };
        });
      }
      option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          timePoints
        },
        grid: {
          left: '3%',
          right: '1%',
          bottom: '2%',
          containLabel: true
        },
        xAxis: [
        {
      type: 'category',
      data: flag?[]:list[0]?.datalist.map(ele => ele.timeReading),
      axisPointer: {
        type: 'shadow'
      }
    }
        ],
        yAxis: [
          {
            type: 'value',
            name: '',
          }
        ],
        series: series
      };
      myChart.clear();
      option && myChart.setOption(option);
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    }
  },
  watch: {
    filterText (newValue) {
      this.filterText = newValue.replace(/^\[(.*?)\]/, '').replace(/\((.*?)\)$/, '')
    }
  },
};
</script>

<style scoped>
.DivisionCarbon{
  height: 100%;
  padding: 10px;
  display: flex;
  .leftbox{
    width: 300px;
    background-color: #fff;
    padding: 20px;
    margin-right: 10px;
    .treebox{
      height: 93%;
      overflow: auto;
    }
  }
  .liftbox{
    width: calc(100% - 310px);
    .righttop{
      height: 80px;
      padding: 20px;
      background-color: #fff;
      margin-bottom: 10px;
    }
    .rightbody{
      height: calc(100% - 90px);
      background-color: #fff;
      padding: 20px;
      .righttitle{
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
      }
      .tableandechart{
        height: 94%;
        .totalechart, .table{
          height: 50%;
        }
        .totalechart{
          padding-top: 10px;
        }
      }
    }
  }
}
::v-deep .el-dialog__footer{
  text-align: center;
}
</style>